﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SJ.Platform.Common;
using SJ.Platform.EFCore.Common;
using SJ.Platform.EFCore.DBOperation.DBOperation.MySQL.Approve;
using SJ.Platform.EFCore.DBOperation.DBOperation.MySQL.Flow;
using SJ.Platform.EFCore.DBOperation.DBOperation.MySQL.Sys;
using SJ.Platform.EFCore.Model;
using SJ.Platform.EFCore.Model.ApproveManager;
using SJ.Platform.EFCore.Model.FlowManager;
using SJ.Platform.EFCore.Model.UserManager;
using SJ.Platform.Extend.IOC.CurrentUser;
using SJ.Platform.Extend.ModelExtend;
using SJ.Platform.Extend.ModelExtend.ApproveExt;
using SJ.Platform.Extend.ModelExtend.ProjectExt;
using SJ.Platform.Extend.Request;
using SJ.Platform.Extend.Response;
using System.Security.Cryptography;

namespace SJ.Platform.Api.Controllers.ApproveManager
{
    /// <summary>
    /// 审批流程操作类
    /// </summary>
    [Route(GlobalVariableHandle.Scope_Api + "/Approve")]
    [ApiController]
    [Authorize(GlobalVariableHandle.Scope_Api)]
    public class ApproveManagerController : ControllerBase
    {
        private readonly SJDBContext _context;
        private readonly ICurrentUser _currentUser;
        private readonly Approve_MainHandle approve_mainHandle;
        private readonly Approve_RecordHandle approve_recordHandle;
        private readonly Flow_NodeHandle flow_nodeHandle;
        private readonly Flow_Node_ApproveUserHandle flow_Node_ApproveUserHandle;
        private readonly Sys_UserHandle sys_UserHandle;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext">数据库</param>
        /// <param name="currentUser">当前用户</param>
        public ApproveManagerController(SJDBContext dbContext, ICurrentUser currentUser)
        {
            _context = dbContext;
            _currentUser = currentUser;
            approve_mainHandle = new Approve_MainHandle(dbContext);
            approve_recordHandle = new Approve_RecordHandle(dbContext);
            flow_nodeHandle = new Flow_NodeHandle(dbContext);
            flow_Node_ApproveUserHandle = new Flow_Node_ApproveUserHandle(dbContext);
            sys_UserHandle = new Sys_UserHandle(dbContext);
        }

        /// <summary>
        /// 新增审批流程
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        [HttpPost("CreateApproveMainAsync")]
        public async Task<IActionResult> CreateApproveMainAsync([FromBody] ApproveMainExtent model)
        {
            try
            {
                bool result = await TransactionHandle.ExecuteInTransactionAsync<bool>(_context, async () =>
                {
                    //主审批流程
                    ApproveMain approveMain = model.ExtMapToEntity<ApproveMain, ApproveMainExtent>();
                    approveMain.Id = Guid.NewGuid().ToString();
                    approveMain.SubmitUserId = _currentUser.UserId;
                    approveMain.SubmitUserName = _currentUser.RealName;
                    approveMain.SubmitTime = DateTime.Now;

                    //审批记录
                    List<ApproveRecord> rList = new List<ApproveRecord>();
                    if (model.approveRecords != null && model.approveRecords.Count > 0)
                    {
                        foreach (var r in model.approveRecords)
                        {
                            r.Id = Guid.NewGuid().ToString();
                            r.PId = approveMain.Id;
                            r.IsCheck = 0;
                            r.CreateTime = DateTime.Now;
                        }
                    }
                    return await approve_mainHandle.CreateAsync(approveMain) && await approve_recordHandle.CreateAsync(model.approveRecords);
                });

                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "审批流程添加" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "审批流程添加失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 修改审批流程
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("UpdateApproveMainAsync")]
        public async Task<IActionResult> UpdateApproveMainAsync([FromBody] ApproveMainExtent model)
        {
            try
            {
                bool result = await TransactionHandle.ExecuteInTransactionAsync<bool>(_context, async () =>
                {
                    ApproveMain approveMain = model.ExtMapToEntity<ApproveMain, ApproveMainExtent>();

                    //先删除审批记录
                    await approve_recordHandle.DeleteByPIdAsync(approveMain.Id);

                    //再添加新的审批记录
                    List<ApproveRecord> rList = new List<ApproveRecord>();
                    if (model.approveRecords != null && model.approveRecords.Count > 0)
                    {
                        foreach (var r in model.approveRecords)
                        {
                            r.Id = Guid.NewGuid().ToString();
                            r.PId = approveMain.Id;
                            r.IsCheck = 0;
                            r.CreateTime = DateTime.Now;
                        }
                    }

                    return await approve_mainHandle.UpdateAsync(approveMain) && await approve_recordHandle.CreateAsync(model.approveRecords);
                });

                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "审批流程修改" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "审批流程修改失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 更新审批流程指定的内容
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("UpdateApproveMainSpecificContentAsync")]
        public async Task<IActionResult> UpdateApproveMainSpecificContentAsync([FromBody] ApproveMainUpdateModelExtend model)
        {
            try
            {
                bool result = await approve_mainHandle.UpdateApproveMainSpecificContentAsync(model);
                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "审批流程更新" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "审批流程更新失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 审批流程
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("DoApproveAsync")]
        public async Task<IActionResult> DoApproveAsync([FromBody] ApproveRecordExtend model)
        {
            try
            {
                int[] result = await TransactionHandle.ExecuteInTransactionAsync<int[]>(_context, async () =>
                {
                    //审批时间
                    model.ApproveTime = DateTime.Now;
                    //已审核
                    model.IsCheck = 1;
                    bool actionResult = await approve_recordHandle.UpdateAsync(model);

                    //获取当前节点的通过条件
                    FlowNode fn = await flow_nodeHandle.GetEntityByIdAsync(model.NodeId);
                    if (actionResult && fn.PassCondition == 1)//一人通过即可
                    {
                        actionResult = await approve_recordHandle.UpdateRecordsByPIdAsync(model.PId);
                    }

                    int passEnd = 0;//审批是否结束，0=未结束，1=结束
                    //一人审批不通过，流程结束
                    if (model.ApproveResult == 2)
                    {
                        passEnd = 1;
                    }

                    //审批同意则找下一个节点
                    if (model.ApproveResult == 1)
                    {
                        //获取当前节点的下一个节点
                        FlowNode nextNode = await flow_nodeHandle.GeFlowNextNodeFromCurrentNodeIdAsync(model.FlowId, model.NodeId);
                        if (actionResult && nextNode != null)
                        {
                            //查询未审核的节点
                            List<ApproveRecord> records = await approve_recordHandle.GetNoCheckRecordsByPIdAndNodeIdAsync(model.PId, model.NodeId);
                            //节点跳转，有下一个节点，且当前节点的通过条件为一人通过即可或者所有的节点都审核完成
                            if (fn.PassCondition == 1 || (fn.PassCondition == 0 && (records == null || records.Count == 0)))
                            {
                                //审批记录
                                List<ApproveRecord> rList = new List<ApproveRecord>();
                                if (nextNode.ApproveType == 1)//专人审批
                                {
                                    List<FlowNodeApproveUser> flowNodeApproveUsers = await flow_Node_ApproveUserHandle.GetEntityListByNodeIdAsync(nextNode.Id);

                                    if (flowNodeApproveUsers != null && flowNodeApproveUsers.Count > 0)
                                    {
                                        foreach (var user in flowNodeApproveUsers)
                                        {
                                            rList.Add(new ApproveRecord
                                            {
                                                Id = Guid.NewGuid().ToString(),
                                                FlowId = model.FlowId,
                                                NodeId = nextNode.Id,
                                                PId = model.PId,
                                                IsCheck = 0,
                                                CreateTime = DateTime.Now,
                                                ApproveUserId = user.ApproveUserId,
                                                ApproveUserName = user.ApproveUserName
                                            });
                                        }
                                    }
                                }

                                if (nextNode.ApproveType == 2)//角色审批
                                {
                                    List<SysUser> sysUsers = await sys_UserHandle.GetAllByRoleId(nextNode.ApproveRoleId);
                                    foreach (var user in sysUsers)
                                    {
                                        rList.Add(new ApproveRecord
                                        {
                                            Id = Guid.NewGuid().ToString(),
                                            FlowId = model.FlowId,
                                            NodeId = nextNode.Id,
                                            PId = model.PId,
                                            IsCheck = 0,
                                            CreateTime = DateTime.Now,
                                            ApproveUserId = user.Id,
                                            ApproveUserName = user.RealName
                                        });
                                    }
                                }

                                if (nextNode.ApproveType == 3)//直属上级审批
                                {

                                }

                                if (nextNode.ApproveType == 4)//其他
                                {
                                    foreach (var item in model.NextApproveRecords)
                                    {
                                        rList.Add(new ApproveRecord
                                        {
                                            Id = Guid.NewGuid().ToString(),
                                            FlowId = model.FlowId,
                                            NodeId = nextNode.Id,
                                            PId = model.PId,
                                            IsCheck = 0,
                                            CreateTime = DateTime.Now,
                                            ApproveUserId = item.ApproveUserId,
                                            ApproveUserName = item.ApproveUserName
                                        });
                                    }
                                }

                                actionResult = await approve_recordHandle.CreateAsync(rList);
                            }
                        }
                        else if (nextNode == null && fn.PassCondition == 0)
                        {
                            List<ApproveRecord> records = await approve_recordHandle.GetNoCheckRecordsByPIdAndNodeIdAsync(model.PId, model.NodeId);
                            if (records == null || records.Count == 0)//没有未审核的
                            {
                                passEnd = 1;
                            }
                        }
                        else if (nextNode == null && fn.PassCondition == 1)
                        {
                            passEnd = 1;
                        }
                    }

                    return new int[2] { actionResult ? 1 : 0, passEnd };
                });

                return Ok(ApiNormalResponse<int>.SetResponse(result[0] == 1 ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "审批流程" + (result[0] == 1 ? "成功" : "失败"), result[1]));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<int>.SetResponse(ApiResponseStatus.BadRequest, "审批流程失败：" + ex.Message, -1));
            }
        }

        /// <summary>
        /// 根据外部流程ID删除审批流程
        /// </summary>
        /// <param name="fId"></param>
        /// <returns></returns>
        [HttpGet("DeleteApproveMainByFIdAsync/{fId}")]
        public async Task<IActionResult> DeleteApproveMainByFIdAsync(string fId)
        {
            try
            {
                bool result = await TransactionHandle.ExecuteInTransactionAsync<bool>(_context, async () =>
                {
                    //找到主流程
                    ApproveMain am = await approve_mainHandle.GetEntityByFIdAsync(fId);
                    return await approve_mainHandle.DeleteByFIdAsync(fId) && await approve_recordHandle.DeleteByPIdAsync(am.Id);
                });

                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "删除审批流程" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "删除审批流程失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 根据审批流程节点ID删除审批流程记录
        /// </summary>
        /// <param name="nodeId"></param>
        /// <returns></returns>
        [HttpGet("DeleteApproveRecordByNodeIdAsync/{nodeId}")]
        public async Task<IActionResult> DeleteApproveRecordByNodeIdAsync(string nodeId)
        {
            try
            {
                bool result = await approve_recordHandle.DeleteByNodeIdAsync(nodeId);

                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "删除审批流程记录" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "删除审批流程记录失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 获取审批流程
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("GetAllApproveMainAsync")]
        public async Task<IActionResult> GetAllApproveMainAsync([FromBody] ApiPageQueryRequest<ApproveMain> request)
        {
            try
            {
                var result = await approve_mainHandle.GetAllAsync((int)request.PageIndex, (int)request.PageSize, ApiPageQueryRequest<ApproveMain>.GenerateCondition(request.Condition));

                return Ok(ApiPageQueryResponse<List<ApproveMain>>.SetResponse(ApiResponseStatus.Success, "查询成功", (int)request.PageIndex, (int)request.PageSize, result.count, result.approves)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiPageQueryResponse<List<ApproveMain>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, (int)request.PageIndex, (int)request.PageSize, 0, new List<ApproveMain> { }));
            }
        }

        /// <summary>
        /// 获取待办审批流程
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("GetWaitToBeDoneApproveMainAsync")]
        public async Task<IActionResult> GetWaitToBeDoneApproveMainAsync([FromBody] ApiPageQueryRequest<ApproveMainExtent> request)
        {
            try
            {
                var result = await approve_mainHandle.GetWaitToBeDoneApproveMainAsync((int)request.PageIndex, (int)request.PageSize, ApiPageQueryRequest<ApproveRecord>.GenerateCondition(request.Condition.ExtMapToEntity<ApproveRecord, ApproveMainExtent>()), ApiPageQueryRequest<ApproveMain>.GenerateCondition(request.Condition.ExtMapToEntity<ApproveMain, ApproveMainExtent>()));

                return Ok(ApiPageQueryResponse<List<ApproveMain>>.SetResponse(ApiResponseStatus.Success, "查询成功", (int)request.PageIndex, (int)request.PageSize, result.count, result.approves)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiPageQueryResponse<List<ApproveMain>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, (int)request.PageIndex, (int)request.PageSize, 0, new List<ApproveMain> { }));
            }
        }

        /// <summary>
        /// 获取当前用户，当前流程的审批信息
        /// </summary>
        /// <param name="approveUserId"></param>
        ///  <param name="pId"></param>
        /// <returns></returns>
        [HttpGet("GetWaitToBeDownRecordAsync/{approveUserId}/{pId}")]
        public async Task<IActionResult> GetWaitToBeDownRecordAsync(string approveUserId, string pId)
        {
            try
            {
                var result = await approve_recordHandle.GetWaitToBeDownRecordAsync(approveUserId, pId);

                return Ok(ApiNormalResponse<ApproveRecord>.SetResponse(ApiResponseStatus.Success, "查询成功", result)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<ApproveRecord>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, new ApproveRecord { }));
            }
        }

        /// <summary>
        /// 获取流程下所有已审核过的审批记录
        /// </summary>
        ///  <param name="pId"></param>
        /// <returns></returns>
        [HttpGet("GetAllCheckedRecordsByPIdAsync/{pId}")]
        public async Task<IActionResult> GetAllCheckedRecordsByPIdAsync(string pId)
        {
            try
            {
                var result = await approve_recordHandle.GetAllCheckedRecordsByPIdAsync(pId);

                return Ok(ApiNormalResponse<List<ApproveRecord>>.SetResponse(ApiResponseStatus.Success, "查询成功", result)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<List<ApproveRecord>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, new List<ApproveRecord> { }));
            }
        }

        /// <summary>
        /// 获取下一个审批节点
        /// </summary>
        /// <param name="approveId"></param>
        /// <param name="flowId"></param>
        /// <param name="nodeId"></param>
        /// <returns></returns>
        [HttpGet("GetNextFlowNodeAsync/{approveId}/{flowId}/{nodeId}")]
        public async Task<IActionResult> GetNextFlowNodeAsync(string approveId, string flowId, string nodeId)
        {
            try
            {
                bool isGetNextNode = false;
                //获取当前节点的通过条件
                FlowNode fn = await flow_nodeHandle.GetEntityByIdAsync(nodeId);
                if (fn.PassCondition == 0)
                {
                    //查询未审核的节点
                    List<ApproveRecord> records = await approve_recordHandle.GetNoCheckRecordsByPIdAndNodeIdAsync(approveId, nodeId);
                    if (records.Count == 1)
                    {
                        isGetNextNode = true;
                    }
                }
                else
                {
                    isGetNextNode = true;
                }


                //获取当前节点的下一个节点
                FlowNode nextNode = new FlowNode();
                if (isGetNextNode)
                {
                    nextNode = await flow_nodeHandle.GeFlowNextNodeFromCurrentNodeIdAsync(flowId, nodeId);
                }

                return Ok(ApiNormalResponse<FlowNode>.SetResponse(ApiResponseStatus.Success, "查询成", nextNode));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<FlowNode>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, new FlowNode { }));
            }
        }
    }
}